<?php

session_start();

$chatLogFile = 'chat.log';
$adminChatLogFile = 'adminChat.log';
$adminTongzhiFile = 'adminTongzhi.log';
$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action == 'sendMessage') {
    $nickname = $_POST['nickname'] ?? '';
    $message = $_POST['message'] ?? '';
    if ($nickname && $message) {
        if (strpos($nickname, '管理员') == false && strpos($message, '管理员') == false) {
            // 将消息追加到文件中
            file_put_contents($chatLogFile, "{$nickname}: {$message}\n", FILE_APPEND);
        }
    }
} elseif ($action == 'adminSendMessage') {

} elseif ($action == 'fetchMessages') {
    // 读取文件内容并返回
    echo nl2br(htmlspecialchars(file_get_contents($adminChatLogFile)));
} elseif ($action == 'fetchAdminMessages') {
    // 读取文件内容并返回
    echo nl2br(htmlspecialchars(file_get_contents($adminChatLogFile)));
} elseif ($action == 'fetchAdminTongzhi') {
      // 读取文件内容并返回
      echo nl2br(htmlspecialchars(file_get_contents($adminTongzhiFile)));
} elseif ($action == 'refreshHotPeople') {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $counterKey = 'peopleCount';
    $currentCount = $redis->get($counterKey);
    echo $currentCount;
} elseif ($action == 'enterChat') {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $counterKey = 'peopleCount';
    $redis->incr($counterKey);
    $nickname = $_POST['nickname'] ?? '';
    // 检查 nickname 长度是否在1到20个字符之间
    if (mb_strlen($nickname) >= 1 && mb_strlen($nickname) <= 20) {
        $simplenickname = $nickname;
    } else {
        $simplenickname = '昵称过长'; // 或者处理错误
    }

    $key = "enterLimit:$simplenickname";
    $ttl = 60; // 键的生存时间，例如，60秒
    if (!$redis->exists($key)) {
        $redis->setex($key, $ttl, '1');
        $_SESSION['nickname'] = $simplenickname;
        $message = date('H:i:s') . " 欢迎「{$simplenickname}」加入";
        file_put_contents($adminChatLogFile, "管理员: {$message}\n", FILE_APPEND);
    } else {
        echo 'chongfu';
    }


} elseif ($action == 'checkNickname') {
    if (isset($_SESSION['nickname'])) {
        echo $_SESSION['nickname'];
    } else {
        echo '';
    }
}